// pages/bookDetail/bookDetail.js
var app = getApp();
var util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    book: {
    },
    username: "",
    modalHidden: true,
    numberVal: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      mask: true,
      title: '加载中...',
    })
    var bookid = options["id"];
    var that = this;
    wx.getStorage({
      key: 'cookie',
      success: function(res) {
        var cookie = res.data;
        var header = util.getCommonHeaders(cookie);
        wx.request({
          url: 'https://bookin.moha.vip/book/' + bookid + "/",
          header: header,
          success: function (res) {
            if(res.statusCode !== 200){
              console.log(res)
              return;
            }
            let max_length = 80;
            if (res.data["data"]["brief_intro"] != null){
              res.data["data"]["brief_intro_portion"] = res.data["data"]["brief_intro"].substr(0, max_length);
              if (res.data["data"]["brief_intro"].length > max_length) {
                res.data["data"]["brief_intro_portion"] += "...";
                that.setData({
                  introduction_full: false
                })
              }
            }
            res.data["data"]["book_pic"] = res.data["data"]["book_pic"].split(" ")
            // for (let i in res.data["data"]["book_pic"]){
            //   res.data["data"]["book_pic"][i] = {
            //     url: res.data["data"]["book_pic"][i],
            //     mode: "aspectFill"
            //   }
            // }
            that.setData({
              book: res.data["data"],
            })
          },
          complete: ()=>{
            wx.hideLoading()
          }
        })
      },
      fail: ()=>{
        wx.hideLoading();
      }
    });
    wx.getStorage({
      key: 'username',
      success: function(res) {
        that.setData({
          username: res.data
        })
      },
    })
  },

  onNumberInput: function(e){
    this.setData({ numberVal: e.detail.value });
  },

  onModalCancel: function(e){
    this.setData({
      modalHidden: true,
      numberVal: ""
    })
  },

  toChat: function(){
    var that = this;
    var id = this.data.book.book_owner_client.user;
    var digest = this.data.book;
    digest.notes = digest.notes.substring(0, 100) + (digest.notes.length > 100 ? "..." : "")
    app.sendTo(id, digest, "book");
    wx.navigateTo({
      url: '/pages/chat/interaction/interaction?id=' + id,
    })
  },

  toBuy: function(){
    this.setData({
      modalHidden: false
    })
  },

  onModalConfirm: function(){
    var that = this;
    if ("" == this.data.numberVal) {
      wx.showToast({
        icon: "none",
        title: '请输入数字',
      });
      return;
    }

    if (isNaN(this.data.numberVal)){
      wx.showToast({
        icon: "none",
        title: '请输入正确的数字！',
      });
      return;
    }
    var num = parseInt(this.data.numberVal);
    if (num <= 0) {
      wx.showToast({
        icon: "none",
        title: '请输入大于0的整数！',
      });
      return;
    }

    if(num > this.data.book.number){
      wx.showToast({
        icon: "none",
        title: '剩余数量不足',
      });
      return;
    }

    wx.showLoading({
      title: '正在提交订单...',
    })
   
    wx.getStorage({
      key: 'cookie',
      success: function(res) {
        var cookie = res.data;
        var header = util.getCommonHeaders(cookie);
        wx.request({
          url: 'https://bookin.moha.vip/transaction/transaction_list/',
          header: header,
          data: {
            "book_id": that.data.book.book_id,
            "number": num
          },
          method: "PUT",
          success: function(e){
            if(e.statusCode == 201){
              wx.showModal({
                title: '提交成功！',
                content: '已经联系卖家进行准备',
                showCancel: false,
                success: (res)=>{
                  wx.navigateBack({})
                }
              });
              var input = "嗨，同学你好！我已经购买了你的书 " + that.data.book.book_name + " 共 " + num + "本，请注意及时处理订单哦~"
              app.sendTo(that.data.book.book_owner_client.user, input, "text");
              that.toChat();
            }else{
              wx.showModal({
                title: '提交失败',
                content: e.data["message"],
                showCancel: false
              });
            }
          },
          fail: function(e){
            wx.showModal({
              title: '提交失败',
              showCancel: false
            });
          }
        })
      },
      complete: function(){
        wx.hideLoading();
        that.onModalCancel();
      }
    })
  },

  toPreview: function(e){
    var imgs = this.data.book.book_pic;
    let index = e.target.dataset.index;
    console.log(e);
    wx.previewImage({
      current: imgs[index], // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },

  toCopy: function(){
    var data = "我正在书荫小程序看《" + this.data.book.book_name + "》，复制这段话到”书荫“就可以看到我看的这本书哦，还等什么？👉👉👉👉 /BOOKIN/book/" + this.data.book.book_id + "/ 👈👈👈👈";
    wx.setClipboardData({
      data: data,
      success: function (res) {
        wx.showToast({
          title: '复制成功！',
        })
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  moreIntro: function(e){
    var more = e.target.dataset.more;
    if(more == "true"){
      this.setData({
        introduction_full: true
      })
    }else{
      this.setData({
        introduction_full: false
      })
    }
  }
})